package cn.powertime.evaluation.file.minio;

import cn.powertime.evaluation.exception.BusinessException;
import cn.powertime.evaluation.file.minio.config.MinioProperties;
import cn.powertime.evaluation.file.storage.FileStorage;
import io.minio.MinioClient;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

/**
 * <p>
 *
 * </p>
 *
 * @author ZYW
 * @version v1.0.0
 * @date 2019-08-23 11:34
 */
@Slf4j
@Configuration
@ConditionalOnClass(MinioClient.class)
@ConditionalOnProperty("noopsyche.resource.minio.enabled")
public class MinioAutoConfiguration {

    @Bean
    public MinioClient minioClient(MinioProperties properties) {
        try {
            return new MinioClient(properties.getEndpoint()
                    ,properties.getPort()
                    ,properties.getAccessKey()
                    ,properties.getSecretKey()
                    ,properties.getSecure());
        } catch (InvalidEndpointException | InvalidPortException e) {
            log.error("create minioclient exception: ", e);
            throw new BusinessException("create minio client exception");
        }
    }

    @Bean
    @DependsOn("minioClient")
    public FileStorage fileStorage(MinioClient minioClient) {
        return new MinioFileStorage(minioClient);
    }

}
